/*******************************************************************************
 * Package: com.practice.security
 * Type:    UserDetailServiceImpl
 * Date:    2023/9/27 11:03
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.practice.security;

import com.practice.constants.Constants;
import com.practice.mapper.UserMapper;
import com.practice.pojo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 登录时会自动调用这个类判断密码知否正确、账号是否禁用等信息
 *
 * @author Masiyu
 * @date 2023/9/27 11:03
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 使用参数s作为参数，调用findAll()方法执行查询
        List<User> all = userMapper.findAll(s);
        // 判断查询结果是否为null
        // 是：无此用户名对应的账号信息，返回null
        if (all.isEmpty()){
            return null;
        }
    
        User user = all.get(0);
        user.setLastLoginTime(new Date());
        userMapper.updateById(user);
        
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority("这是临时使用的一个山寨的权限");
        authorities.add(authority);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
        // 返回UserDetails对象
        return  new UserDetail(
                user.getId(),
                user.getName(),
                user.getStatus(),
                user.getPassword(),
                user.getStatus().equals(Constants.USER_NORMAL),
                authorities);
    }
}
